package com.sky.service.impl;

import com.sky.dto.GoodsSalesDTO;
import com.sky.mapper.OrderMapper;
import com.sky.mapper.UserMapper;
import com.sky.service.OrderService;
import com.sky.service.ReportService;
import com.sky.service.WorkspaceService;
import com.sky.vo.*;
import io.swagger.models.auth.In;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.*;

@Service
@Slf4j
public class ReportServiceImpl implements ReportService {
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private WorkspaceService workspaceService;
    /**
     * 营业额数据统计
     * @param begin
     * @param end
     * @return
     * 查订单表
     */
    @Override
    public TurnoverReportVO getStatics(LocalDate begin, LocalDate end) {
        //日期类型可以相加
        List<LocalDate> localDateList =new ArrayList<>();
        localDateList.add(begin);

        while (!begin.equals(end)){
            begin = begin.plusDays(1);
            localDateList.add(begin);
        }
        List<Double> turnoverList =new ArrayList<>();
        for (LocalDate localDate : localDateList) {
            //查询每个日期对应的数据
            //算无限接近的时间
            LocalDateTime beginTime= LocalDateTime.of(localDate, LocalTime.from(LocalDateTime.MIN));
            LocalDateTime endTime= LocalDateTime.of(localDate, LocalTime.from(LocalDateTime.MAX));
            Map map=new HashMap();
            map.put("beginTime",beginTime);
            map.put("endTime",endTime);
            map.put("status",5);
            Double turnover=orderMapper.sumByMap(map);
            if (turnover==null){
                turnover=0.0;
            }
            turnoverList.add(turnover);
        }
        return new TurnoverReportVO(StringUtils.join(localDateList,","),StringUtils.join(turnoverList,","));
    }

    @Override
    public UserReportVO getUserStatics(LocalDate begin, LocalDate end) {
        List<LocalDate> localDateList =new ArrayList<>();
        localDateList.add(begin);
        /**
         * 类似上步
         */
        while (!begin.equals(end)){
            begin = begin.plusDays(1);
            localDateList.add(begin);
        }
        List<Integer> totalUserList =new ArrayList<>();//总用户
        List<Integer> newUserList=new ArrayList<>();//新增用户
        for (LocalDate localDate : localDateList) {
            //查询每个日期对应的数据
            //算无限接近的时间
            LocalDateTime beginTime= LocalDateTime.of(localDate, LocalTime.from(LocalDateTime.MIN));
            LocalDateTime endTime= LocalDateTime.of(localDate, LocalTime.from(LocalDateTime.MAX));
            Map map=new HashMap();
            map.put("begin",beginTime);
            map.put("end",endTime);
            //获取当天及之前的用户总人数
            Integer currentSum= userMapper.getByTotalUserNumberBeforeLimtDate(map);
            totalUserList.add(currentSum);
            //获取当天新增用户人数
            Integer newNum=userMapper.getNewTotalUser(map);
            newUserList.add(newNum);
        }
        return new UserReportVO(StringUtils.join(localDateList,","),StringUtils.join(totalUserList,","),StringUtils.join(newUserList,","));
    }

    @Override
    public OrderReportVO getOrderStatics(LocalDate begin, LocalDate end) {
        List<LocalDate> localDateList =new ArrayList<>();
        localDateList.add(begin);
        while (!begin.equals(end)){
            begin = begin.plusDays(1);
            localDateList.add(begin);
        }
        List<Integer> orderCountList=new ArrayList<>();//每日订单总数
        List<Integer> validOrderCountList=new ArrayList<>();//每日订单有效总数
        for (LocalDate localDate : localDateList) {
            //查询每个日期对应的数据
            //算无限接近的时间
            LocalDateTime beginTime= LocalDateTime.of(localDate, LocalTime.from(LocalDateTime.MIN));
            LocalDateTime endTime= LocalDateTime.of(localDate, LocalTime.from(LocalDateTime.MAX));
            Map map=new HashMap();
            map.put("beginTime",beginTime);
            map.put("endTime",endTime);
            //每日订单总数
            Integer currentTotalNum=orderMapper.allCountByTime(map);
            //每日有效订单总数
            map.put("status",5);
            Integer validTotalNum=orderMapper.allCountByTime(map);

            orderCountList.add(currentTotalNum);
            validOrderCountList.add(validTotalNum);
        }
        //订单总数
        Integer totalOrderCount=orderMapper.allCount();
        //有效订单数-已完成-status-5
        Integer validOrderCount=orderMapper.validCount();
        //订单完成率
        Double finishRate=  ((double)validOrderCount/ (double)totalOrderCount);
        return new OrderReportVO(StringUtils.join(localDateList,","),StringUtils.join(orderCountList,","),StringUtils.join(validOrderCountList,","),totalOrderCount,validOrderCount,finishRate);
    }

    @Override
    public SalesTop10ReportVO getTop10(LocalDate begin, LocalDate end) {
        LocalDateTime beginTime= LocalDateTime.of(begin, LocalTime.from(LocalDateTime.MIN));
        LocalDateTime endTime= LocalDateTime.of(end, LocalTime.from(LocalDateTime.MAX));

        List<GoodsSalesDTO> salesTop = orderMapper.getSalesTop(beginTime, endTime);
        System.out.println("salesTop:"+salesTop);
        System.out.println("salesTop:"+salesTop.size());
        System.out.println("salesTop:"+salesTop);
        System.out.println("salesTop:"+salesTop.size());
        System.out.println("salesTop:"+salesTop);
        List<String> goodsNameList=new ArrayList<>();
        for (GoodsSalesDTO goodsSalesDTO : salesTop) {
            goodsNameList.add(goodsSalesDTO.getName());
        }
        List<Integer> numberList =new ArrayList<>();
        for (GoodsSalesDTO goodsSalesDTO : salesTop) {
            numberList.add(goodsSalesDTO.getNumber());
        }

        return new SalesTop10ReportVO(StringUtils.join(goodsNameList,","),StringUtils.join(numberList,","));
    }
    //运营数据报表
    @Override
    public void exportData(HttpServletResponse response) throws IOException {

        //1.查询数据库，获取相关数据

        //当前时间 要算前一天因为今天的数据还可能变动
        LocalDate end = LocalDate.now().minusDays(1);
        //30天前日期
        LocalDate begin = LocalDate.now().minusDays(30);
        //查询概览数据
        BusinessDataVO businessData = workspaceService.getBusinessData(LocalDateTime.of(begin, LocalTime.MIN), LocalDateTime.of(end, LocalTime.MAX));

        //2.写入excel
        //通过类加载器重新创建一个新文件
        InputStream resourceAsStream = this.getClass().getClassLoader().getResourceAsStream("template/运营数据报表模板.xlsx");
        //填充数据---时间
        XSSFWorkbook excel = new XSSFWorkbook(resourceAsStream);
        XSSFSheet sheet= excel.getSheet("Sheet1");

        sheet.getRow(1).getCell(1).setCellValue("时间:"+begin+"至"+end);//获取第二行 第二个单元格

        XSSFRow row = sheet.getRow(3);
        row.getCell(2).setCellValue(1);
        sheet.getRow(3).getCell(4).setCellValue(businessData.getOrderCompletionRate());
        sheet.getRow(3).getCell(6).setCellValue(businessData.getNewUsers());

        sheet.getRow(4).getCell(2).setCellValue(businessData.getValidOrderCount());
        sheet.getRow(4).getCell(4).setCellValue(businessData.getUnitPrice());

        int rowIndex=7;
        //明细数据
        for (int i = 0; i < 30; i++) {
            LocalDate date = begin.plusDays(i);
            //查询某天营业数据
            LocalDateTime.of(date, LocalTime.MIN);
            BusinessDataVO businessData1 = workspaceService.getBusinessData(LocalDateTime.of(date, LocalTime.MIN), LocalDateTime.of(date, LocalTime.MAX));
            XSSFRow rows = sheet.getRow(rowIndex+i);
            rows.getCell(1).setCellValue(date.toString());
            rows.getCell(2).setCellValue(businessData1.getTurnover());
            rows.getCell(3).setCellValue(businessData1.getValidOrderCount());
            rows.getCell(4).setCellValue(businessData1.getOrderCompletionRate());
            rows.getCell(5).setCellValue(businessData1.getUnitPrice());
            rows.getCell(6).setCellValue(businessData1.getNewUsers());
            businessData1.setTurnover(0.0);
        }

        //3.下载到浏览器
        ServletOutputStream outputStream = response.getOutputStream();
        excel.write(outputStream);
        outputStream.close();
        excel.close();
    }
}